/**
 * File: InitGraphController.java
 * Created by: mhaimel
 * Created on: Apr 20, 2010
 * CVS:  $Id: InitGraphController.java 1.0 Apr 20, 2010 4:06:40 PM mhaimel Exp $
 */
package uk.ac.ebi.curtain.controller.graph;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import uk.ac.ebi.curtain.controller.SingleSubmitController;
import uk.ac.ebi.curtain.model.graph.Graph;
import uk.ac.ebi.curtain.model.graph.Node;
import uk.ac.ebi.curtain.model.graph.GraphAccess.TouchEach;
import uk.ac.ebi.curtain.model.graph.curtain.ContigInfo;
import uk.ac.ebi.curtain.model.graph.curtain.CurtainGraph;
import uk.ac.ebi.curtain.model.graph.curtain.ReadWrapper;
import uk.ac.ebi.curtain.model.graph.impl.ConcurrentGraph;
import uk.ac.ebi.curtain.service.IdentifierStore;
import uk.ac.ebi.curtain.utils.CurtainUncheckedException;
import uk.ac.ebi.curtain.utils.data.FileType;
import uk.ac.ebi.curtain.utils.data.ReadType;
import uk.ac.ebi.curtain.utils.file.EntryMapper;
import uk.ac.ebi.curtain.utils.file.EntryMapperBean;
import uk.ac.ebi.curtain.utils.file.FileInfo;

/**
 * @author mhaimel
 *
 */
public class InitGraphController extends SingleSubmitController<Serializable, Serializable> {

	@Override
	protected void singleSubmit(List<Serializable> inputList) {
		Integer ctgSize = getContext().getContigIndex().getSize();
		int categories = getContext().getArguments().getCategories().size();
		final Graph<ContigInfo, ReadWrapper> graph = new ConcurrentGraph<ContigInfo, ReadWrapper>(ctgSize.longValue());
		final CurtainGraph curtainGraph = new CurtainGraph(categories, graph);
		final IdentifierStore<String, Integer> idx = getContext().getContigIndex();
		for(FileInfo fi : getContext().getArguments().getFiles(ReadType.Contig, FileType.values())){
			fi.getFileType().getParser().parse(fi, new EntryMapper() {
				
				@Override
				public void mapEntry(EntryMapperBean bean) {
					Integer id = idx.getIdentifier(bean.getId());
					Node<ContigInfo, ReadWrapper> node = curtainGraph.getEmptyNode(id.longValue(), (long)bean.getSequenceLength());
					ContigInfo value = node.getValue();
					value.getCategories();
				}
			});
		}
		final AtomicInteger cnt = new AtomicInteger(0);
		graph.processNodes(new TouchEach<Node<ContigInfo,ReadWrapper>>(){

			@Override
			public void touch(Node<ContigInfo, ReadWrapper> node) {
				if(null == node){
					cnt.incrementAndGet();
				}
			}});
		File gFile = getContext().currentFiles().getGraph("Nodes");
		try {
			curtainGraph.persist(gFile);
		} catch (IOException e) {
			throw new CurtainUncheckedException("Problems persisting Graph to " + gFile);
		}
		getContext().setGraph(curtainGraph);
		if(cnt.get() > 0){
			throw new IllegalStateException("Not all Contig nodes filled! Empty nodes: "+cnt.get());
		}
		getLog().info("Finished filling Graph with Contigs!");
		for(Serializable s : inputList){
			submit(s);
		}
	}
	
}














